package com.su.lightthings.viewmodel

import android.bluetooth.BluetoothAdapter
import android.bluetooth.BluetoothDevice
import android.os.Handler
import android.os.Looper
import android.os.Message
import android.util.Log
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import com.kunminx.architecture.domain.message.MutableResult
import com.su.lightthings.bean.ReceiveDataBean
import com.su.lightthings.bluetooth.BtUtil
import com.su.lightthings.service.BluetoothService
import com.su.lightthings.utils.Cons
import java.util.UUID

class BleViewModel : ViewModel() {
    companion object {
        private const val TAG = "BleViewModel"

        val INSTANCE: BleViewModel by lazy {
            BleViewModel()
        }
    }

    //服务的Binder
    var binder: BluetoothService.MyBinder? = null

    //蓝牙扫描状态
    val scanState = MutableLiveData("")


    //设备功能列表
    val functionList = MutableLiveData<MutableList<Int>>(mutableListOf())

    //Android的BluetoothAdapter
    var btAdapter: BluetoothAdapter? = null

    //当前是否有手表已经连接
    var isWatchConnected = MutableResult(false)

    // ble连接状态,用来控制连接弹窗
    // 0:无状态 1:未连接 2:连接中 3:已连接
    var bleConnectState = MutableLiveData(-1)

    //收到手表发来的数据
    var bleData: MutableResult<ReceiveDataBean> = MutableResult<ReceiveDataBean>()
    var rawData: MutableLiveData<String> = MutableLiveData<String>()


    /**
     * 获取功能列表
     */
    fun getFunctionList() {
        if (!isWatchConnected.value!!) return
        binder?.write(BtUtil.makeWriteData(1, 1, Cons.BondFunctionId.FUNCTION_LIST))
    }

    /**
     * 更新功能列表
     */
    fun updateFunctionList(funcList: MutableList<Int>) {
        this.functionList.postValue(funcList)
    }

    /**
     * 更新ble设备连接状态
     */
    fun updateConnectState(state: Int?) {
        this.bleConnectState.postValue(state)
    }


    /**
     * 开始扫描BLE设备
     */
    fun startScanBle() {
        this.binder?.startScanBle()
    }

    /**
     * 停止扫描BLE设备
     */
    fun stopScanBle() {
        this.binder?.stopScanBle()
    }

    /**
     * 连接设备：通过BLE设备进行连接
     * @param device BLE设备
     */
    fun connectBle(device: BluetoothDevice) {
        btAdapter?.let {
            this.binder?.connectBle(device)
        }
    }

    /**
     * 连接设备：通过BLE设备进行连接
     * @param device BLE设备
     */
    fun disconnectBle() {
        this.binder?.disconnect()
    }

    /**
     * 向ble设备发送数据
     */
    fun write(data: ByteArray): Boolean? {
        Log.d(TAG, "向ble设备发送数据: ${data.contentToString()}")
        val device = ConnectViewModel.INSTANCE.deviceConnectionMLD.value?.device
        Log.d(TAG, "device == null : ${device == null}")
        if (device != null) {
            return this.binder?.write(data)
        }
        return false
    }

    /**
     * 向ble设备发送数据
     */
    fun write(device: BluetoothDevice, data: ByteArray): Boolean? {
        Log.d(TAG, "向ble设备发送数据")
        return this.binder?.write(device, data)
    }


    /**
     * 向ble设备发送数据
     */
    fun write(serviceUUID: UUID, characteristicUUID: UUID, data: ByteArray): Boolean? {
        Log.d(TAG, "向ble设备发送数据")
        Log.d(TAG, "向ble设备发送数据")
        val device = ConnectViewModel.INSTANCE.deviceConnectionMLD.value?.device
        Log.d(TAG, "device == null : ${device == null}")
        if (device != null) {
            return this.binder?.write(serviceUUID, characteristicUUID, data)
        }
        return false
    }

    /**
     * 终止BLE监听
     *
     * @param type 0:常规数据 1:杰里
     */
    fun disableBLEDeviceNotification(type: Int) {
        Log.d(TAG, "终止监听：$type")
        this.binder?.disableBLEDeviceNotification(type)
    }

    /**
     * 开启BLE监听
     *
     * @param type 0:常规数据 1:杰里
     */
    fun enableBLEDeviceNotification(type: Int) {
        Log.d(TAG, "开启监听：$type")
        this.binder?.enableBLEDeviceNotification(type)
    }


    private val mHandler = object : Handler(Looper.myLooper()!!) {
        override fun handleMessage(msg: Message) {
            super.handleMessage(msg)
            Log.d(TAG, "handle Thread: ${Thread.currentThread().name}")
            if (msg.what == 1) {
                bleData.value =
                    msg.obj as ReceiveDataBean
            }
        }
    }
}